#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <net/if.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if_arp.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>

char *mac_ntoa(unsigned char *ptr) {
	static char address[30];
	sprintf(address, "%02X:%02X:%02X:%02X:%02X:%02X",
	ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
	return(address);
}

int myArp(char * ip)
{
	struct arpreq arpRequest;
	bzero((caddr_t)&arpRequest, sizeof(arpRequest));
	strcpy(arpRequest.arp_dev, "eth0");
	
	struct sockaddr_in *sin;
	sin = (struct sockaddr_in *)&arpRequest.arp_pa;
	sin->sin_family = AF_INET;
	if (!inet_pton(AF_INET, ip, &(sin->sin_addr.s_addr))) {
		perror("IP address error");
		exit(-1);
	}
	
	int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {    
        perror ("Error from socket call");
        return (-1);
    }

    if (ioctl(sockfd, SIOCGARP, (caddr_t)&arpRequest) < 0) {
		if(errno == ENXIO){
			printf("%s -- no entry.\n", ip);
			close(sockfd);
			exit(-1);
		}
        perror ("SIOCGARP");
        close(sockfd);
        return (-1);
    }

    printf("IP: %s, MAC: %s\n", ip, mac_ntoa(arpRequest.arp_ha.sa_data));

    close(sockfd);
    return 0;
}

int main(int argc, char **argv) {
    if (argc != 2) {
        printf("Wrong number of arguments! Usage: myarp <IP>\n");
        return -1;
    } 
    myArp(argv[1]);
    return 0;
}
